import { useState, useEffect } from 'react';
import { Button, Input, Label, Text, Spinner, Table, TableHeader, TableRow, TableHead, TableBody, TableCell, Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, DialogClose } from 'packages/ui-shared/src/atoms';
import { useSession } from '../hooks/useSession';
import { AuditLogService, AuditAction } from '@packages/shared';

// 角色权限配置
interface RolePermission {
  id: string;
  name: string;
  description: string;
  permissions: string[];
}

// 预定义角色配置
const defaultRoles: RolePermission[] = [
  {
    id: 'admin',
    name: '管理员',
    description: '拥有系统所有权限',
    permissions: [
      'user.create', 'user.read', 'user.update', 'user.delete',
      'role.assign', 'audit.view', 'audit.export', 'system.settings'
    ]
  },
  {
    id: 'user',
    name: '用户',
    description: '拥有基础操作权限',
    permissions: [
      'user.read', 'audit.view'
    ]
  },
  {
    id: 'guest',
    name: '访客',
    description: '仅拥有查看权限',
    permissions: [
      'dashboard.view'
    ]
  }
];

// 权限列表
const allPermissions = [
  { id: 'user.create', name: '创建用户', description: '可以添加新用户' },
  { id: 'user.read', name: '查看用户', description: '可以查看用户列表' },
  { id: 'user.update', name: '编辑用户', description: '可以修改用户信息' },
  { id: 'user.delete', name: '删除用户', description: '可以删除用户' },
  { id: 'role.assign', name: '分配角色', description: '可以分配用户角色' },
  { id: 'audit.view', name: '查看审计日志', description: '可以查看操作日志' },
  { id: 'audit.export', name: '导出审计日志', description: '可以导出日志文件' },
  { id: 'system.settings', name: '系统设置', description: '可以修改系统配置' },
  { id: 'dashboard.view', name: '查看仪表板', description: '可以查看仪表板' }
];

export default function RoleManagementPage() {
  const { session } = useSession();
  const [roles, setRoles] = useState<RolePermission[]>(defaultRoles);
  const [loading, setLoading] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [currentRole, setCurrentRole] = useState<RolePermission | null>(null);
  const [selectedPermissions, setSelectedPermissions] = useState<string[]>([]);
  const [alert, setAlert] = useState('');
  const [showAlert, setShowAlert] = useState(false);

  // 检查权限
  const canManageRoles = session?.userRole === 'admin';

  useEffect(() => {
    if (!canManageRoles) {
      setAlert('您没有权限访问此页面');
      setShowAlert(true);
    }
  }, [canManageRoles]);

  // 编辑角色
  const handleEditRole = (role: RolePermission) => {
    setCurrentRole(role);
    setSelectedPermissions([...role.permissions]);
    setShowEditDialog(true);
  };

  // 保存角色权限
  const handleSaveRole = async () => {
    if (!currentRole || !session) return;

    setLoading(true);
    try {
      // 更新角色权限
      const updatedRoles = roles.map(role => 
        role.id === currentRole.id 
          ? { ...role, permissions: selectedPermissions }
          : role
      );
      setRoles(updatedRoles);

      // 记录审计日志
      await AuditLogService.log(
        session.userId,
        session.userName,
        session.userRole,
        AuditAction.ROLE_ASSIGN,
        `修改角色权限: ${currentRole.name}`,
        true,
        {
          roleId: currentRole.id,
          oldPermissions: currentRole.permissions,
          newPermissions: selectedPermissions
        }
      );

      setShowEditDialog(false);
      setCurrentRole(null);
      setAlert('角色权限更新成功');
      setShowAlert(true);
    } catch (error) {
      console.error('保存角色权限失败:', error);
      setAlert('保存失败');
      setShowAlert(true);
    } finally {
      setLoading(false);
    }
  };

  // 切换权限选择
  const togglePermission = (permissionId: string) => {
    setSelectedPermissions(prev => 
      prev.includes(permissionId)
        ? prev.filter(id => id !== permissionId)
        : [...prev, permissionId]
    );
  };

  // 获取权限名称
  const getPermissionName = (permissionId: string) => {
    const permission = allPermissions.find(p => p.id === permissionId);
    return permission ? permission.name : permissionId;
  };

  if (!canManageRoles) {
    return (
      <div className="p-6">
        <div className="text-center">
          <Text className="text-xl text-red-500">访问被拒绝</Text>
          <Text className="text-gray-500 mt-2">您没有权限访问角色管理页面</Text>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6">
      {/* 页面头部 */}
      <div className="mb-6">
        <Text className="text-2xl font-bold text-gray-900 mb-2">角色管理</Text>
        <Text className="text-gray-600">管理系统角色和权限配置</Text>
      </div>

      {/* 提示信息 */}
      {showAlert && (
        <div className="mb-4 p-3 bg-green-100 border border-green-500 rounded shadow-sm">
          <Text className="font-semibold text-green-700">{alert}</Text>
        </div>
      )}

      {/* 角色列表 */}
      <div className="bg-white rounded-lg shadow overflow-hidden">
        <div className="px-6 py-4 border-b border-gray-200">
          <Text className="text-lg font-semibold">系统角色</Text>
        </div>

        <div className="overflow-x-auto">
          <Table className="min-w-full">
            <TableHeader className="bg-gray-50">
              <TableRow>
                <TableHead className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  角色信息
                </TableHead>
                <TableHead className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  权限数量
                </TableHead>
                <TableHead className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  权限列表
                </TableHead>
                <TableHead className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  操作
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody className="bg-white divide-y divide-gray-200">
              {roles.map((role) => (
                <TableRow key={role.id} className="hover:bg-gray-50">
                  <TableCell className="px-6 py-4 whitespace-nowrap">
                    <div>
                      <Text className="text-sm font-medium text-gray-900">
                        {role.name}
                      </Text>
                      <Text className="text-sm text-gray-500">
                        {role.description}
                      </Text>
                    </div>
                  </TableCell>
                  <TableCell className="px-6 py-4 whitespace-nowrap">
                    <span className="inline-flex px-2 py-1 text-xs font-semibold rounded-full bg-blue-100 text-blue-800">
                      {role.permissions.length} 个权限
                    </span>
                  </TableCell>
                  <TableCell className="px-6 py-4">
                    <div className="flex flex-wrap gap-1">
                      {role.permissions.slice(0, 3).map((permission) => (
                        <span
                          key={permission}
                          className="inline-flex px-2 py-1 text-xs font-medium rounded bg-gray-100 text-gray-800"
                        >
                          {getPermissionName(permission)}
                        </span>
                      ))}
                      {role.permissions.length > 3 && (
                        <span className="inline-flex px-2 py-1 text-xs font-medium rounded bg-gray-100 text-gray-800">
                          +{role.permissions.length - 3} 更多
                        </span>
                      )}
                    </div>
                  </TableCell>
                  <TableCell className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <Button
                      size="sm"
                      onClick={() => handleEditRole(role)}
                      variant="outline"
                    >
                      编辑权限
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      </div>

      {/* 编辑角色权限对话框 */}
      <Dialog open={showEditDialog} onOpenChange={setShowEditDialog}>
        <DialogContent size="lg">
          <DialogHeader>
            <DialogTitle>编辑角色权限</DialogTitle>
            <DialogDescription>
              为角色 "{currentRole?.name}" 配置权限
            </DialogDescription>
          </DialogHeader>

          <div className="py-4">
            <div className="space-y-4">
              <div>
                <Text className="text-sm font-medium text-gray-700 mb-3">
                  选择权限
                </Text>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3 max-h-96 overflow-y-auto">
                  {allPermissions.map((permission) => (
                    <label
                      key={permission.id}
                      className="flex items-start space-x-3 p-3 border rounded-lg hover:bg-gray-50 cursor-pointer"
                    >
                      <input
                        type="checkbox"
                        checked={selectedPermissions.includes(permission.id)}
                        onChange={() => togglePermission(permission.id)}
                        className="mt-1 h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                      />
                      <div className="flex-1 min-w-0">
                        <Text className="text-sm font-medium text-gray-900">
                          {permission.name}
                        </Text>
                        <Text className="text-xs text-gray-500">
                          {permission.description}
                        </Text>
                      </div>
                    </label>
                  ))}
                </div>
              </div>

              <div className="pt-4 border-t">
                <Text className="text-sm text-gray-600">
                  已选择 {selectedPermissions.length} 个权限
                </Text>
              </div>
            </div>
          </div>

          <DialogFooter>
            <DialogClose>取消</DialogClose>
            <Button 
              variant="primary" 
              onClick={handleSaveRole}
              disabled={loading}
            >
              {loading ? <Spinner size="sm" className="mr-2" /> : null}
              保存权限
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
